import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_string_util_lib.dart';

class NavigatorPageObserver extends NavigatorObserver{
  ///挂起保留视频状态
  final VoidCallback onPush;

  ///还原挂起前视频状态
  final VoidCallback onPop;

  BuildContext context;

  ///路由名区别页面ID
  String _routeNameId;

  NavigatorPageObserver(
      this.context, {
        @required this.onPush,
        @required this.onPop,
      }) {
    Future(() {
      _routeNameId = ModalRoute.of(context).settings?.name;
      print("获取routeName:${_routeNameId}");
    });
  }

  ///注册监听
  void addObserver() {
    if (AppMain.context == null) {
      return;
    }
    Navigator.of(AppMain.context)?.widget?.observers?.add(this);
    print("注册 NavigatorPageObserver 监听");
  }

  ///解绑监听
  void removeObserver() {
    if (AppMain.context == null) {
      return;
    }
    Navigator.of(AppMain.context)?.widget?.observers?.remove(this);
    print("移除 NavigatorPageObserver 监听");
  }

  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    if (_isCurrentPage(previousRoute?.settings?.name)) {
      if (onPush != null) {
        onPush();
      }
    }
  }

  @override
  void didPop(Route route, Route previousRoute) {

    if (_isCurrentPage(previousRoute?.settings?.name)) {
      if (onPop != null) {
        onPop();
      }
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
    print("测试：didRemove");
  }

  bool _isCurrentPage(String resultRouteName) {
    // return ModalRoute.of(context)?.isCurrent ?? false;
    if (StringUtils.isEmpty(_routeNameId) ||
        StringUtils.isEmpty(resultRouteName)) {
      return false;
    }
    return resultRouteName == _routeNameId;
  }
}